<template>
  <div class="login__container" ref="backgroundRef">
    <div class="login-title" v-if="system"><img v-if="!xinzhou" src="/src/assets/login/login-title.png" alt="点津问道标品">
    </div>
    <div class="login-content">
      <!-- <h1>欢迎登录</h1> -->
      <div class="loginType"><div :class="loginType === 0 ? 'active' : ''" @click="loginType = 0;errorMsg=''">用户名登录</div><div
          :class="loginType === 1 ? 'active' : ''" @click="loginType = 1;errorMsg=''" class="code">验证码登录</div></div>
      <el-form :model="formGroup" :rules="rules" ref="formRef">
        <div v-if="loginType == 0">
          <el-form-item prop="mobile">
            <el-input placeholder="请输入用户名" prefix-icon="el-icon-user" v-model="formGroup.mobile" />
          </el-form-item>
          <el-form-item prop="md5Password">
            <el-input placeholder="请输入密码" :type="showPassword ? 'test' : 'password'" prefix-icon="el-icon-lock"
              v-model="formGroup.md5Password">
              <template #suffix>
                <div @click="showPassword = !showPassword" class="show-password-icon">
                  <img v-if="showPassword" src="/src/assets/login/login-password-show.png" />
                  <img v-else src="/src/assets/login/login-password-hide.png" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <div class="login-remember">
            <p @click="forgetPassword" style="cursor: pointer;">忘记密码</p>
            <p style="color: red;">{{ errorMsg }}</p>
          </div>
        </div>
        <div v-if="loginType === 1">
          <el-form-item>
            <el-input placeholder="请输入手机号" prefix-icon="el-icon-user" v-model="formGroup.phone" />
          </el-form-item>
          <el-form-item>
            <el-input placeholder="请输入验证码" prefix-icon="el-icon-lock"
              v-model="formGroup.code" style="width:55%">
            </el-input>
            <el-button style="width:40%;margin-left: 11px;padding:9px 20px" @click="sendCode" :disabled="timer > 0">{{
      timer > 0
        ? `${timer}秒后重发` : '发送验证码' }}</el-button>
          </el-form-item>
          <div class="login-remember">
            <p style="color: red;">{{ errorMsg }}</p>
          </div>
        </div>
        <el-button type="primary" :loading="saveLoading" @click="login">登 录</el-button>
      </el-form>
    </div>
    <div class="foot"><a href="https://beian.miit.gov.cn/" target="_blank">备案号：豫ICP备2024054129号-1</a></div>
  </div>
</template>

<script lang="ts">
import { ref, Ref, reactive } from "vue";
import md5 from "js-md5";
import { ElMessage, ElLoading } from "element-plus";
import { useStore } from "vuex";
import { SET_USER_INFO,REMOVE_SUBJECT_LIST, REMOVE_USER_INFO } from "@/store/types";
import { useRouter } from "vue-router";
import $ from '$';
import backgroundImage1 from '@/assets/login/bg-11.jpg';

import ForgetPasswordComponent from '../layout/components/forget-password.vue';
// import backgroundImage2 from '@/assets/login/login-bg-2.jpg';
// import backgroundImage3 from '@/assets/login/login-bg-3.jpg';

export default {
  setup() {
    $.drawer.closeAll();
    $.modal.closeAll();
    $.screen.closeAll();
    let xinzhou = import.meta.env.VITE_IS_XINZHOU
    const system = import.meta.env.VITE_IS_BIAOPIN;
    let loginType = ref(0);
    let remember = ref(false);
    let showPassword = ref(false);
    let formRef = ref();
    let store = useStore();
    let router = useRouter();
    let saveLoading = ref(false);
    let rememberAccount = $.storage.get('account') || {};
    let formGroup = reactive({
      mobile: rememberAccount.mobile,
      md5Password: rememberAccount.md5Password,
      phone: '',
      code: '',
    });
    let timer = ref(0);
    let errorMsg = ref('');
    let rules = {
      mobile: [{ required: true, message: "请输入用户名" }],
      md5Password: [{ required: true, message: "请输入密码" }],
    };

    store.commit(REMOVE_USER_INFO);
        store.commit(REMOVE_SUBJECT_LIST);
        router.push('/login');
        localStorage.removeItem('cartListValue')//重新登陆时清空
        localStorage.removeItem('sliderWidth')
        localStorage.clear();
        
    const login = async () => {
      errorMsg.value = ''
      let res = { result: false, json: { accessToken: '' }, msg: '' };
      if (loginType.value === 0) {
        await formRef.value.validate();
        let params = {
          mobile: formGroup.mobile,
          md5Password: md5(formGroup.md5Password),
          loginType: 1
        };
        saveLoading.value = true;
        if (remember.value) { $.storage.set('account', formGroup) } else { $.storage.remove('account') }
        res = await $.http.post("/permission/auth/login", params);
      } else {
        if (formGroup.phone === '') {
          errorMsg.value = "请输入手机号";
          return;
        }
        let reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
        if (!reg.test(formGroup.phone)) {
          errorMsg.value = "请输入正确的手机号";
          return;
        }

        if (formGroup.code === '') {
          errorMsg.value = "验证码不能为空";
          return;
        }
        var nreg = /^\d{4}$/;
        if (!nreg.test(formGroup.code)) {
          errorMsg.value = "验证码格式不正确";
          return;
        }
        let params = {
          mobile: formGroup.phone,
          code:formGroup.code,
          loginType: 1
        };
        res = await $.http.post("/permission/auth/loginByCode", params);
      }

      saveLoading.value = false;
      if (res && res.result) {
        store.commit(SET_USER_INFO, res.json);

        $.storage.set('token', res.json.accessToken);
        router.push("/home");
      } else {
        // ElMessage.warning(res.msg);
        errorMsg.value = res.msg;
      }
    };

    let loading = ElLoading.service();
    let backgroundRef: Ref<HTMLElement | null> = ref(null);
    let index = Math.floor(Math.random() * 1);
    let image = new Image();
    let url = [backgroundImage1][index]
    image.src = url;
    image.onload = () => {
      setTimeout(() => loading.close());
      backgroundRef.value!.style.background = `url(${url}) center center / cover no-repeat`;
    }
    const sendCode = async () => {
      // 这里可以加入对手机的合法性校验
      if (formGroup.phone === '') {
        errorMsg.value = "请输入手机号";
        return;
      }
      let reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
      if (!reg.test(formGroup.phone)) {
        errorMsg.value = "请输入正确的手机号";
        return;
      }
      errorMsg.value = "";
      // 发送请求，获取验证码
      try {
        // Replace with real API call
        let res = await $.http.post("/permission/auth/sendCheckCode", { mobile: formGroup.phone });
        if (!res.result) {
          // ElMessage.error(res.msg);
          errorMsg.value = res.msg;
          return
        }else{
          errorMsg.value = "";
        }
        timer.value = 60; // 设定倒计时的时间

        let countdown = setInterval(() => {
          if (timer.value > 0) {
            timer.value--;
          } else {
            clearInterval(countdown);
          }
        }, 1000);

      } catch (error) {
        console.error('Error:', error);
      }

    };
    const forgetPassword = () => {
      $.modal.create({ title: '修改密码', width: 400, component: ForgetPasswordComponent })
    }
    return { backgroundRef, showPassword, remember, formRef, formGroup, rules, login, saveLoading, system, xinzhou, loginType, timer, errorMsg, sendCode,forgetPassword };
  },
};
</script>

<style lang="scss">
.login__container {
  height: 100%;
  position: relative;
  overflow: hidden;

  .login-title {
    width: 15%;
    position: absolute;
    top: 50px;
    left: 160px;

    img {
      width: 100%
    }
  }

  .login-content {
    width: 360px;
    padding: 40px 36px 60px;
    border-radius: 10px;
    background: rgba(15, 15, 15, .6);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(200px, -200px, 0);

    h1 {
      color: #fff;
      font-size: 22px;
      line-height: 40px;
      text-align: center;
      margin-bottom: 30px;
    }

    .loginType {
      display: flex;
      width: 100%;
      border-bottom: solid 2px white;
      margin-bottom: 50px;
      color: white;
      height: 30px;
      div {
        height: 30px;
        cursor: pointer;
        padding-left: 20px;
        padding-right: 20px;
      }

      .code {
        margin-left: 68px;
      }

      .active {
        border-bottom: solid 2px #72b22a;
        color: #72b22a;
      }
    }


    .el-input__inner {
      border-radius: 6px;
    }

    .el-input__prefix {
      font-size: 16px;
    }

    .show-password-icon {
      cursor: pointer;
    }

    .el-button {
      width: 100%;
      font-size: 16px;
      border-radius: 8px;
    }
  }

  .login-remember {
    height: 16px;
    color: #91a5c2;
    font-size: 14px;
    line-height: 16px;
    margin-bottom: 30px;
    text-align: center;

    .login__label {
      display: inline-block;
      position: relative;
      cursor: pointer;

      &::before {
        content: "";
        display: inline-block;
        width: 16px;
        height: 16px;
        border-radius: 4px;
        background: #72b22a;
      }

      i {
        color: #fff;
        position: absolute;
        top: 2px;
        left: 1px;
      }

      span {
        display: inline-block;
        margin-left: 6px;
        color: #fff;
        vertical-align: top;
      }
    }

    p {
      color: #fff;
    }
  }

  .foot {
    position: absolute;
    bottom: 10px;
    text-align: center;
    width: 100%;
  }
}
</style>
